package com.bnzj.core.util;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConstructorUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BeanConvertUtils {

    /**
     * 把List<Map<K,V>>转换为List<T>
     * @param listMap
     * @param resultClass
     * @return
     * @throws Exception
     */
    public static <T> List<T> convertListMapToListBean(List<Map<String, Object>> listMap, Class<T> resultClass) throws Exception {
        List<T> beanList = new ArrayList<T>();
        for (int i = 0, n = listMap.size(); i < n; i++) {
            Map<String, Object> map = listMap.get(i);
            T bean = ConstructorUtils.invokeConstructor(resultClass, null);
            BeanUtils.populate(bean, map);
            beanList.add(bean);
        }
        return beanList;
    }

    /**
     * 把List<T>转换为List<Map<K,V>>
     * @param listMap
     * @param resultClass
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> convertListBeanToListMap(List<?> beanList) throws Exception {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (int i = 0, n = beanList.size(); i < n; i++) {
            Object bean = beanList.get(i);
            PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(bean);
            Map<String, Object> map = new HashMap<String, Object>();
            for (PropertyDescriptor descriptor : descriptors) {
                final String name = descriptor.getName();
                Object value = PropertyUtils.getProperty(bean, name);
                map.put(name, value);
            }
            mapList.add(map);
        }
        return mapList;
    }
    
    /**
     * 获取对象的属性值为空的属性名称
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        return emptyNames.toArray(new String[emptyNames.size()]);
    }
    
    public static Object getProperty(Object bean, String fieldName) {
        try {
            return PropertyUtils.getProperty(bean, fieldName);
        } catch (Exception e) {
            log.error("类{}找不到{}属性", bean.getClass().getName(), fieldName);
            return null;
        }
    }
}
